<template>
  <div class="vip-payment-page" :class="{ 'dark': isDark }">
    <!-- 自定义标题栏 (Electron环境) -->
    <div class="custom-titlebar">
      <div class="titlebar-content">
        <div class="title">
          <el-icon><CreditCard /></el-icon>
          {{ t('dashboard.vipCenter.vipPayment.title') }}
        </div>
        <div class="titlebar-controls">
          <el-button 
            text 
            @click="goBack"
            class="back-btn"
          >
            <el-icon><ArrowLeft /></el-icon>
            {{ t('dashboard.vipCenter.vipPayment.back') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 支付内容区域 -->
    <div class="payment-content">
      <div v-if="loading" class="loading-container">
        <el-loading-icon />
        <p>{{ t('dashboard.vipCenter.vipPayment.loadingPayment') }}</p>
      </div>
      
      <div v-else-if="error" class="error-container">
        <el-result
          icon="error"
          :title="t('dashboard.vipCenter.vipPayment.paymentLoadFailed')"
          :sub-title="error"
        >
          <template #extra>
            <el-button type="primary" @click="goBack">{{ t('dashboard.vipCenter.vipPayment.backRetry') }}</el-button>
          </template>
        </el-result>
      </div>

      <!-- 支付HTML内容容器 -->
      <div 
        v-else
        id="payment-html-container"
        class="payment-html-container"
        v-html="paymentHtml"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { CreditCard, ArrowLeft } from '@element-plus/icons-vue'
import { useVipStore } from '@/stores/vip'
import { useThemeStore } from '@/stores/theme'

const router = useRouter()
const { t } = useI18n()
const vipStore = useVipStore()
const themeStore = useThemeStore()

// 计算当前是否为暗色模式
const isDark = computed(() => themeStore.isDark)

const loading = ref(true)
const error = ref('')
const paymentHtml = ref('')
const orderNo = ref('')

// 监听支付结果的消息
const handlePaymentMessage = (event: MessageEvent) => {
  if (event.data && event.data.type === 'PAYMENT_SUCCESS') {
    ElMessage.success(t('dashboard.vipCenter.vipPayment.paymentSuccess'))
    
    // 刷新VIP状态
    vipStore.fetchVipStatus()
    
    // 跳转到支付结果页面
    router.push({
      path: '/pay-result',
      query: {
        success: 'true',
        orderNo: event.data.orderNo || orderNo.value,
        message: t('dashboard.vipCenter.paymentResult.messages.vipActivatedSuccess')
      }
    })
  } else if (event.data && event.data.type === 'PAYMENT_CANCEL') {
    ElMessage.warning(t('dashboard.vipCenter.vipPayment.paymentCancelled'))
    goBack()
  }
}

onMounted(async () => {
  try {
    // 从sessionStorage获取支付HTML内容
    const storedHtml = sessionStorage.getItem('vipPaymentHtml')
    const storedOrderNo = sessionStorage.getItem('vipOrderNo')
    
    if (!storedHtml) {
      throw new Error(t('dashboard.vipCenter.vipPayment.paymentInfoExpired'))
    }

    paymentHtml.value = storedHtml
    orderNo.value = storedOrderNo || ''
    
    // 清除sessionStorage
    sessionStorage.removeItem('vipPaymentHtml')
    sessionStorage.removeItem('vipOrderNo')
    
    loading.value = false

    // 添加消息监听器
    window.addEventListener('message', handlePaymentMessage)
    
    // 等待DOM更新后，设置支付页面中的回调函数
    await nextTick()
    setupPaymentCallbacks()
    
  } catch (err: any) {
    console.error('加载支付页面失败:', err)
    error.value = err.message || t('dashboard.vipCenter.vipPayment.paymentLoadFailed')
    loading.value = false
  }
})

onUnmounted(() => {
  window.removeEventListener('message', handlePaymentMessage)
})

// 设置支付页面中的回调函数
const setupPaymentCallbacks = () => {
  // 重写支付页面中的JavaScript函数
  const script = document.createElement('script')
  script.textContent = `
    // 重写模拟支付成功函数
    window.simulateSuccess = function() {
      const btn = event.target;
      btn.disabled = true;
      btn.innerHTML = '⏳ ${t('dashboard.vipCenter.vipPayment.processing')}';
      
      const params = new URLSearchParams({
        out_trade_no: '${orderNo.value}',
        trade_no: 'MOCK_' + Date.now(),
        trade_status: 'TRADE_SUCCESS',
        total_amount: '29.90'
      });
      
      // 延迟1秒模拟网络请求
      setTimeout(() => {
        // 调用后端Mock支付接口
        fetch('http://localhost:8080/api/payment/mock/return?' + params.toString(), {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(response => response.text())
        .then(html => {
          // 解析返回结果
          const tempDiv = document.createElement('div');
          tempDiv.innerHTML = html;
          
          const successElement = tempDiv.querySelector('[data-success]');
          const messageElement = tempDiv.querySelector('[data-message]');
          
          const isSuccess = successElement ? successElement.getAttribute('data-success') === 'true' : true;
          const message = messageElement ? messageElement.textContent : '${t('dashboard.vipCenter.paymentResult.messages.vipActivatedSuccess')}';
          
          // 将结果存储到sessionStorage
          sessionStorage.setItem('paymentSuccess', isSuccess.toString());
          sessionStorage.setItem('paymentOrderNo', '${orderNo.value}');
          sessionStorage.setItem('paymentMessage', message);
          
          // 跳转到结果页面
          window.location.href = '/pay-result';
        })
        .catch(error => {
          console.error('支付请求失败:', error);
          sessionStorage.setItem('paymentSuccess', 'false');
          sessionStorage.setItem('paymentOrderNo', '${orderNo.value}');
          sessionStorage.setItem('paymentMessage', '${t('dashboard.vipCenter.vipPayment.paymentProcessFailed')}');
          window.location.href = '/pay-result';
        });
      }, 1000);
    };
    
    // 重写取消支付函数
    window.simulateCancel = function() {
      // 发送取消消息给父窗口
      window.parent.postMessage({
        type: 'PAYMENT_CANCEL'
      }, '*');
    };
  `
  document.head.appendChild(script)
}

const goBack = () => {
  router.back()
}
</script>

<style scoped>
.vip-payment-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fafbfc;
  transition: background-color 0.2s ease;
}

.vip-payment-page.dark {
  background: #0f172a;
}

/* 自定义标题栏样式 */
.custom-titlebar {
  height: 40px;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  color: #1f2937;
  border-bottom: 1px solid #e5e7eb;
  transition: all 0.2s ease;
}

.vip-payment-page.dark .custom-titlebar {
  background: #1e293b;
  color: #f1f5f9;
  border-bottom: 1px solid #334155;
}

.titlebar-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.titlebar-controls {
  -webkit-app-region: no-drag;
}

.back-btn {
  color: #6b7280 !important;
  padding: 4px 8px !important;
  border-radius: 6px !important;
  transition: all 0.2s ease;
}

.back-btn:hover {
  background: #f3f4f6 !important;
  color: #374151 !important;
}

.vip-payment-page.dark .back-btn {
  color: #94a3b8 !important;
}

.vip-payment-page.dark .back-btn:hover {
  background: #334155 !important;
  color: #e2e8f0 !important;
}

/* 内容区域 */
.payment-content {
  flex: 1;
  overflow: auto;
  position: relative;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 16px;
  color: #6b7280;
}

.error-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.payment-html-container {
  height: 100%;
  width: 100%;
  overflow: auto;
  padding: 32px 24px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 支付页面样式重写 */
.payment-html-container :deep(html),
.payment-html-container :deep(body) {
  margin: 0 !important;
  padding: 0 !important;
  height: auto !important;
  min-height: auto !important;
  background: transparent !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
}

.payment-html-container :deep(.container) {
  max-width: 420px !important;
  margin: 0 auto !important;
  padding: 0 !important;
  background: transparent !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  display: block !important;
}

.payment-html-container :deep(.payment-form) {
  background: #fff !important;
  border-radius: 16px !important;
  padding: 32px 28px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06) !important;
  border: none !important;
  transition: all 0.2s ease !important;
}

.vip-payment-page.dark .payment-html-container :deep(.payment-form) {
  background: #1e293b !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2) !important;
}

.payment-html-container :deep(h1) {
  color: #111827 !important;
  font-size: 24px !important;
  font-weight: 600 !important;
  margin: 0 0 24px 0 !important;
  text-align: center !important;
  letter-spacing: -0.025em !important;
  transition: color 0.2s ease !important;
}

.vip-payment-page.dark .payment-html-container :deep(h1) {
  color: #f1f5f9 !important;
}

.payment-html-container :deep(.order-info) {
  background: #f9fafb !important;
  padding: 20px !important;
  border-radius: 12px !important;
  margin: 0 0 24px 0 !important;
  border: none !important;
  transition: background-color 0.2s ease !important;
}

.vip-payment-page.dark .payment-html-container :deep(.order-info) {
  background: #0f172a !important;
}

.payment-html-container :deep(.order-item) {
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  margin: 0 0 12px 0 !important;
  color: #4b5563 !important;
  font-size: 14px !important;
  transition: color 0.2s ease !important;
}

.payment-html-container :deep(.order-item:last-child) {
  margin-bottom: 0 !important;
}

.vip-payment-page.dark .payment-html-container :deep(.order-item) {
  color: #94a3b8 !important;
}

.payment-html-container :deep(.order-item strong),
.payment-html-container :deep(.total-amount) {
  font-size: 16px !important;
  font-weight: 600 !important;
  color: #111827 !important;
  transition: color 0.2s ease !important;
}

.vip-payment-page.dark .payment-html-container :deep(.order-item strong),
.vip-payment-page.dark .payment-html-container :deep(.total-amount) {
  color: #f1f5f9 !important;
}

.payment-html-container :deep(.payment-buttons) {
  display: flex !important;
  flex-direction: column !important;
  gap: 12px !important;
  margin-top: 0 !important;
}

.payment-html-container :deep(.btn) {
  width: 100% !important;
  padding: 12px 20px !important;
  border: none !important;
  border-radius: 8px !important;
  font-size: 15px !important;
  font-weight: 500 !important;
  cursor: pointer !important;
  transition: all 0.15s ease !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 8px !important;
}

.payment-html-container :deep(.btn-success) {
  background: #10b981 !important;
  color: white !important;
}

.payment-html-container :deep(.btn-success:hover:not(:disabled)) {
  background: #059669 !important;
}

.payment-html-container :deep(.btn-secondary) {
  background: #f3f4f6 !important;
  color: #6b7280 !important;
  border: none !important;
  transition: all 0.2s ease !important;
}

.payment-html-container :deep(.btn-secondary:hover:not(:disabled)) {
  background: #e5e7eb !important;
  color: #4b5563 !important;
}

.vip-payment-page.dark .payment-html-container :deep(.btn-secondary) {
  background: #334155 !important;
  color: #94a3b8 !important;
}

.vip-payment-page.dark .payment-html-container :deep(.btn-secondary:hover:not(:disabled)) {
  background: #475569 !important;
  color: #e2e8f0 !important;
}

.payment-html-container :deep(.btn:disabled) {
  opacity: 0.5 !important;
  cursor: not-allowed !important;
}

.payment-html-container :deep(.qr-code) {
  margin: 24px 0 !important;
  text-align: center !important;
  padding: 16px !important;
  background: #f9fafb !important;
  border-radius: 8px !important;
  border: none !important;
  transition: background-color 0.2s ease !important;
}

.vip-payment-page.dark .payment-html-container :deep(.qr-code) {
  background: #0f172a !important;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .payment-html-container {
    padding: 16px;
  }
  
  .payment-html-container :deep(.payment-form) {
    padding: 24px 20px !important;
  }
  
  .payment-html-container :deep(h1) {
    font-size: 20px !important;
  }
}

@media (max-height: 600px) {
  .payment-html-container {
    padding: 16px;
    align-items: flex-start;
  }
}
</style>